<template>
  <el-col :span="24">
    <el-card shadow="hover">
      <template #header>
        <el-button type="primary" :icon="Plus" @click="showAddTrademarkDialog"
          >添加品牌</el-button
        >
      </template>
      <el-table
        :data="trademarkList"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column
          prop="date"
          type="index"
          label="序号"
          width="80"
          align="center"
        />
        <el-table-column prop="tmName" label="品牌名称" />
        <el-table-column label="品牌LOGO">
          <template v-slot="{ row }">
            <el-image style="width: 100px" :src="row.logoUrl" :is="row" />
          </template>
        </el-table-column>
        <el-table-column prop="Address" label="操作">
          <template v-slot="{ row }">
            <el-button
              type="warning"
              :icon="Edit"
              size="small"
              @click="showUpdateTrademarkDialog(row)"
            ></el-button>
            <el-button
              type="danger"
              :icon="Delete"
              size="small"
              @click="delTrademark(row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 45, 20]"
        layout=" prev, pager, next, jumper,->,total, sizes"
        :total="total"
        @size-change="getTrademarkList"
        @current-change="getTrademarkList"
        class="pagination"
      />
    </el-card>
    <el-dialog
      v-model="dialogTableVisible"
      :title="`${formData.id ? '修改' : '添加'}品牌`"
    >
      <el-form
        label-width="120px"
        ref="formRef"
        :model="formData"
        :rules="formRules"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="formData.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${BASE__URL}/admin/product/fileUpload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            accept="image/jpeg,image/png"
          >
            <img
              v-if="formData.logoUrl"
              :src="formData.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png格式的图片，且小于200kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="submit"> 确定 </el-button>
          <el-button type="primary" @click="dialogTableVisible = false">
            取消
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-col>
</template>

<script lang="ts">
export default {
  name: "XTrademark",
};
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import {
  getTrademarkListApi,
  addTrademarkApi,
  updateTrademarkApi,
  delTrademarkApi,
} from "@/api/product/trademark";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type {
  TrademarkList,
  TrademarkItem,
} from "@/api/product/type/trademarkType";
import type { UploadProps } from "element-plus";
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(100);
const loading = ref(false);
const dialogTableVisible = ref(false);
const trademarkList = ref<TrademarkList>([]);
const BASE__URL = import.meta.env.VITE_API_URL;
// 删除品牌
const delTrademark = (row: TrademarkItem) => {
  ElMessageBox.confirm(`确定要删除${row.tmName}吗`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await delTrademarkApi(row.id);
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      getTrademarkList();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};
// 添加品牌
const showAddTrademarkDialog = () => {
  formData.logoUrl = "";
  formData.tmName = "";
  dialogTableVisible.value = true;
};
// 修改品牌
const showUpdateTrademarkDialog = async (row: TrademarkItem) => {
  formData.logoUrl = row.logoUrl;
  formData.tmName = row.tmName;
  formData.id = row.id;
  dialogTableVisible.value = true;
};
// 表单数据类型
const formData = reactive({
  id: 0,
  logoUrl: "",
  tmName: "",
});
// 图片上传成功
const handleAvatarSuccess: UploadProps["onSuccess"] = (res) => {
  console.log(res);
  formData.logoUrl = res.data;
};
// 图片上传格式
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const fileType = ["image/jpeg", "image/png"];
  if (!fileType.includes(rawFile.type)) {
    ElMessage.error("上传文件只能是jpg和png格式");
    return false;
  } else if (rawFile.size / 1024 > 200) {
    ElMessage.error("文件不能超过200kb");
    return false;
  }
  return true;
};

// 表单校验
// 获取表单实例对象
const formRef = ref();
// // 提交数据
// 校验数据
const formRules = reactive({
  tmName: [
    { required: true, message: "请输入表单名称", trigger: "blur" },
    { min: 2, max: 10, message: "表单名称长度必须在2—10位", trigger: "blur" },
  ],
  logoUrl: [{ required: true, message: "请输入LOGO" }],
});
// 提交表单
const submit = async () => {
  dialogTableVisible.value = false;
  // 对表单进行校验
  await formRef.value.validate();
  if (!formData.id) {
    await addTrademarkApi(formData.logoUrl, formData.tmName);
  } else {
    await updateTrademarkApi(formData);
  }
  getTrademarkList();
};
// 商品品牌数据获取展示
const getTrademarkList = async () => {
  loading.value = true;
  const res = await getTrademarkListApi(currentPage.value, pageSize.value);
  // console.log(res);

  trademarkList.value = res.records;
  total.value = res.total;
  loading.value = false;
};
// 请求商品品牌数据
onMounted(getTrademarkList);
</script>

<style scoped>
.pagination {
  margin-top: 20px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
